package com.yj.auto.component.base.service;

import java.util.ArrayList;
import java.util.List;

import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.SqlPara;
import com.yj.auto.component.base.model.DocType;
import com.yj.auto.core.base.annotation.Service;
import com.yj.auto.core.base.model.QueryModel;
import com.yj.auto.core.jfinal.base.BaseService;

/**
 * DocType 管理 描述：
 */
@Service(name = "docTypeSrv")
public class DocTypeService extends BaseService<DocType> {

	private static final Log logger = Log.getLog(DocTypeService.class);

	public static final String SQL_LIST = "component.doc.type.list";

	public static final DocType dao = new DocType().dao();

	@Override
	public DocType getDao() {
		return dao;
	}

	@Override
	public SqlPara getListSqlPara(QueryModel query) {
		if (StrKit.isBlank(query.getOrderby())) {
			query.setOrderby("sort");
		}
		return getSqlPara(SQL_LIST, query);
	}

	public boolean save(DocType model) {
		boolean success = model.save();
		if (success) {
			updatePath(model);
		}
		return success;
	}

	public boolean update(DocType model) {
		boolean success = model.update();
		if (success) {
			updatePath(model);
		}
		return success;
	}

	private void updatePath(DocType model) {
		DocType temp = model;
		String path = "," + model.getId() + ",";
		while (temp.getParentId() != 0) {
			DocType parent = this.get(temp.getParentId());
			if (null == parent) {
				break;
			} else {
				path = "," + parent.getId() + path;
			}
			temp = parent;
		}
		model.setPath(path);
		model.update();
	}

	public List<DocType> children(Integer id, String state) {
		if (null == id)
			id = new Integer(0);
		QueryModel query = new QueryModel();
		query.setId(id);
		query.setState(state);
		query.setOrderby("sort");
		return find(SQL_LIST, query);
	}

	public boolean updateSort(Integer[] id) {
		if (null == id || id.length < 1)
			return false;
		List<DocType> list = new ArrayList<DocType>();
		for (int i = 0; i < id.length; i++) {
			DocType d = new DocType();
			d.setId(id[i]);
			d.setSort(i + 1);
			list.add(d);
		}
		String sql = "update t_com_doc_type set sort=? where id=?";
		int[] result = Db.batch(sql, "sort, id", list, 500);
		return result.length > 0;
	}
}